// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef CLOUDAPPSDK_CASSTREAMRECVPARSE_H
#define CLOUDAPPSDK_CASSTREAMRECVPARSE_H

#include <array>
#include <map>
#include <mutex>
#include <thread>
#include "CasMsg.h"
#include "CasPktHandle.h"
#include "CasSocket.h"

class CasStreamRecvParser {
public:
    static CasStreamRecvParser *GetInstance();

    static void DestroyInstance();

    CasPktHandle *GetServiceHandle(unsigned char type);

    void SetServiceHandle(unsigned char type, CasPktHandle *serviceHandle);

private:
    CasStreamRecvParser();

    ~CasStreamRecvParser();

    static CasStreamRecvParser *g_instance;
    std::array<CasPktHandle *, CasMsgType::End> m_serviceHandles;
};

class CasStreamParseThread {
public:
    CasStreamParseThread(CasSocket *socket, CasStreamRecvParser *streamRecvParser);

    ~CasStreamParseThread();

    int Start();

    int Stop();

private:
    std::thread m_task;
    volatile int m_threadStatus;
    std::mutex m_lock;
    CasSocket *m_socket;
    CasStreamRecvParser *m_streamRecvParser;

    friend void HandleCompletePktMsg(CasStreamParseThread *streamParseThread, streamMsgHead *msgHead,
        unsigned char *recvBuf, unsigned int pktStartPos);

    friend void RecvDataTaskEntry(CasStreamParseThread *streamParseThread);
};

#endif // CLOUDAPPSDK_CASSTREAMRECVPARSE_H
